const mongoose = require('mongoose');
const glob = require('glob');
const path = require('path');
const dbAddress = 'mongodb://118.25.208.36:1024/mpvueBooks' // 远程地址，这里使用ip，不能使用域名


let connnectCount = 0

exports.connectDb = () => {
  function connect() {
    mongoose.connect(dbAddress, {
      useNewUrlParser: true,
      useCreateIndex: true
    })
  }
  connect()
  mongoose.connection.on('disconnected', () => {
    if (connnectCount < 3) {
      connect()
      connnectCount++
    } else {
      throw new Error('数据库连接失败')
    }
  })
  mongoose.connection.on('error', () => {
    if (connnectCount < 3) {
      connect()
      connnectCount++
    } else {
      throw new Error('数据库连接错误')
    }
  })

  mongoose.connection.once('open', () => {
    console.log('数据库连接成功');
  })
}
exports.initSchema = () => {
  glob.sync(path.resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}
